package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetCareService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetCareRecordV0;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/pet-care")
@Tag(name = "宠物日常护理模块")
public class PetCareController {
    @Autowired
    PetCareService petCareService;
    
    @Autowired
    cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetCareRecordMapper petCareMapper;
    
    // ==================== 管理后台接口 ====================
    
    @Operation(summary = "管理员查询宠物护理记录（支持动态查询）")
    @GetMapping({"/admin/list", "/admin/pet-care/list"})
    // @PreAuthorize("hasRole('ADMIN')")  // 如需启用权限，取消注释
    public PageResult<PetCareRecordV0> getAdminPetCareList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物ID") @RequestParam(required = false) Long petId,
            @Parameter(description = "宠物名称（模糊查询）") @RequestParam(required = false) String petName,
            @Parameter(description = "护理类型") @RequestParam(required = false) Integer careType,
            @Parameter(description = "护理员工ID") @RequestParam(required = false) Long employeeId,
            @Parameter(description = "员工姓名（模糊查询）") @RequestParam(required = false) String employeeName,
            @Parameter(description = "护理开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "护理结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "最短护理时长（分钟）") @RequestParam(required = false) Integer minDuration,
            @Parameter(description = "最长护理时长（分钟）") @RequestParam(required = false) Integer maxDuration,
            @Parameter(description = "护理状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "排序字段") @RequestParam(required = false) String orderBy,
            @Parameter(description = "排序方向") @RequestParam(required = false, defaultValue = "desc") String order
    ) {
        try {
            log.info("管理员查询宠物护理记录 - pageNum: {}, pageSize: {}, petId: {}, petName: {}, careType: {}", 
                     pageNum, pageSize, petId, petName, careType);
            log.info("筛选条件 - 员工: {} (ID: {}), 日期: [{} - {}], 时长: [{} - {}], 状态: {}", 
                     employeeName, employeeId, startDate, endDate, minDuration, maxDuration, status);
            
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord> queryWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            
            // 1. 宠物ID
            if (petId != null) {
                queryWrapper.eq(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getPetId, petId);
            }
            
            // 2. 宠物名称（需要关联查询）
            if (org.springframework.util.StringUtils.hasText(petName)) {
                if (petId == null) {
                    // 通过子查询实现宠物名称模糊查询
                    queryWrapper.apply("pet_id IN (SELECT id FROM pets WHERE pet_name LIKE {0})", 
                                      "%" + petName + "%");
                }
            }
            
            // 3. 护理类型（Integer字段）
            if (careType != null) {
                queryWrapper.eq(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareType, careType);
            }
            
            // 4. 员工ID
            if (employeeId != null) {
                queryWrapper.eq(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getEmployeeId, employeeId);
            }
            
            // 5. 员工姓名（需要关联查询）
            if (org.springframework.util.StringUtils.hasText(employeeName)) {
                if (employeeId == null) {
                    // 通过子查询实现员工姓名模糊查询
                    queryWrapper.apply("employee_id IN (SELECT id FROM employees WHERE employee_name LIKE {0})", 
                                      "%" + employeeName + "%");
                }
            }
            
            // 6. 日期范围
            if (org.springframework.util.StringUtils.hasText(startDate)) {
                queryWrapper.ge(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareDate, startDate);
            }
            if (org.springframework.util.StringUtils.hasText(endDate)) {
                queryWrapper.le(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareDate, endDate);
            }
            
            // 7. 护理时长范围（注意：PetCareRecord可能没有duration字段，这里假设有或通过计算得出）
            // 如果数据库没有duration字段，可以通过careTime计算，或者忽略此参数
            if (minDuration != null || maxDuration != null) {
                // 注意：如果PetCareRecord没有duration字段，需要注释掉这部分
                // 或者通过其他方式计算（如通过careTime字段）
                log.warn("护理时长筛选功能需要数据库有duration字段，当前可能不支持");
                // queryWrapper.ge(PetCareRecord::getDuration, minDuration);
                // queryWrapper.le(PetCareRecord::getDuration, maxDuration);
            }
            
            // 8. 护理状态（注意：PetCareRecord可能没有status字段）
            if (status != null) {
                // 如果数据库有status字段，使用：
                // queryWrapper.eq(PetCareRecord::getStatus, status);
                // 否则需要注释掉或通过其他字段判断
                log.warn("护理状态筛选功能需要数据库有status字段，当前可能不支持");
            }
            
            // 9. 排序
            if (org.springframework.util.StringUtils.hasText(orderBy)) {
                boolean isAsc = "asc".equalsIgnoreCase(order);
                if ("careDate".equalsIgnoreCase(orderBy)) {
                    queryWrapper.orderBy(true, isAsc, cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareDate);
                } else if ("careTime".equalsIgnoreCase(orderBy)) {
                    queryWrapper.orderBy(true, isAsc, cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareTime);
                } else {
                    queryWrapper.orderByDesc(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getId);
                }
            } else {
                queryWrapper.orderByDesc(cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareDate, 
                                        cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord::getCareTime);
            }
            
            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord> page = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord> result = 
                    petCareMapper.selectPage(page, queryWrapper);
            
            log.info("管理员查询护理记录结果 - 总记录数: {}, 当前页: {}, 总页数: {}", 
                     result.getTotal(), result.getCurrent(), result.getPages());
            
            // 转换为VO（这里简化处理，实际应该有完整的VO转换）
            java.util.List<PetCareRecordV0> voList = new java.util.ArrayList<>();
            for (cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord record : result.getRecords()) {
                PetCareRecordV0 vo = petCareService.getCareRecordDetailById(record.getId());
                if (vo != null) {
                    voList.add(vo);
                }
            }
            
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<PetCareRecordV0> voPage = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(result.getCurrent(), result.getSize(), result.getTotal());
            voPage.setRecords(voList);
            
            return PageResult.success(voPage);
        } catch (Exception e) {
            log.error("管理员查询护理记录失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }
    
    // ==================== 用户端接口 ====================

    @Operation(summary = "查询宠物的日常护理记录列表")
    @GetMapping("/list")
    public PageResult<PetCareRecordV0> getPageByPetId(
            @Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(name = "size", defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物ID") @RequestParam(name = "petId", required = false) Long petId,
            @Parameter(description = "宠物名称") @RequestParam(name = "petName", required = false) String petName,
            @Parameter(description = "护理类型") @RequestParam(name = "careType", required = false) String careType) {
        try {
            log.info("接收到查询宠物护理资料的分页查询，petId:{}, petName:{}, careType:{}", petId, petName, careType);
            Page<PetCareRecordV0> page = petCareService.getPageByPetId(pageNum, pageSize, petId);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询宠物护理资料失败, petId: {}", petId, e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查看单条护理记录详情")
    @GetMapping("/detail/{id}")
    public Result<PetCareRecordV0> getCareRecordDetail(
            @Parameter(description = "护理记录ID") @PathVariable Long id) {
        try {
            PetCareRecordV0 record = petCareService.getCareRecordDetailById(id);
            if (record != null) {
                return Result.success(record);
            }
            return Result.error("记录不存在");
        } catch (Exception e) {
            log.error("查询护理记录详情失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(summary = "添加宠物的日常护理记录")
    @PostMapping({"/create", ""})
    public Result<?> createCareRecord(@RequestBody cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord record) {
        try {
            boolean success = petCareService.createCareRecord(record);
            return success ? Result.success("添加成功") : Result.error("添加失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("添加护理记录失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    @Operation(summary = "修改护理记录信息")
    @PutMapping("/update/{id}")
    public Result<?> updateCareRecord(
            @Parameter(description = "护理记录ID") @PathVariable Long id,
            @RequestBody cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.PetCareRecord record) {
        try {
            record.setId(id);
            boolean success = petCareService.updateCareRecord(record);
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新护理记录失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除护理记录")
    @DeleteMapping({"/delete/{id}", "/{id}"})
    public Result<?> deleteCareRecord(
            @Parameter(description = "护理记录ID") @PathVariable Long id) {
        try {
            boolean success = petCareService.deleteCareRecord(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除护理记录失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}

